#!/bin/bash

### BEGIN INIT INFO
# Provides:          adnsonde
# Required-Start:
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start ADN SONDE daemon
# Description:       Enable service provided by ADN SONDE daemon.
### END INIT INFO

# chkconfig: 2345 71 31

INITSCRIPT="$(basename "$0")"
JOB="${INITSCRIPT%.sh}"
ADN=adnsonde

if [ -z "$1" ]; then  
    echo "Usage : $JOB start|restart|stop|status\n"
    exit 1
else
    COMMAND="$1"
    shift
fi

PIDADN=$(ps -C adnsonde 2> /dev/null | awk '/[0-9]/ { print $1 }')
PIDPERL=$(head -n 1 /tmp/ADN/adn.pid)

function status {
	if [ -z "$PIDADN" ]; then
		echo -e "\033[40;31;1m \t*\033[m $ADN not running"
	fi
	if [ -z "$PIDPERL" ]; then
		echo -e "\033[40;31;1m \t*\033[m perl not running"		
	fi
	if [ -n "$PIDADN" ] && [ -n "$PIDPERL" ]; then
		echo -e "\t---------------------------------"
		echo -e "\tPID ADNSONDE: \033[40;32;1m$PIDADN\033[m"
		echo -e "\tPID PERL: \033[40;32;1m$PIDPERL\033[m"
		echo -e "\t$ADN is running"
		echo -e "\t---------------------------------\n"
	fi
	return
}

function start {
	su - root -c "$ADN" > /dev/null 2>&1 &
	sleep 1
	PIDADN=$(ps -C adnsonde 2> /dev/null | awk '/[0-9]/ { print $1 }')
    	PIDPERL=$(head -n 1 /tmp/ADN/adn.pid)
	if [ -z "$PIDADN" ]; then
		echo -e "\n \033[40;31;1m \t*\033[m Fail start $ADN"		
		exit 1	
	fi
	echo -e "\n \033[40;32;1m \t*\033[m Start PID: $PIDADN NAME: $ADN"
	echo -e "\033[40;32;1m \t*\033[m Start PID: $PIDPERL NAME: perl"
	return
}

function stop {
	if [ -n "$PIDADN" ]; then
		echo -e "\033[40;31;1m \t*\033[m Kill PID: $PIDADN NAME: $ADN"
		kill  $PIDADN
		sleep 1		
	fi
	if [ -n "$PIDPERL" ]; then	
		echo -e "\033[40;31;1m \t*\033[m Kill PID: $PIDPERL NAME: perl"
		kill -s INT $PIDPERL
	fi
	if [ -f "/tmp/ADN/adn.pid" ]; then
		rm /tmp/ADN/adn.pid
	fi
	return
}

function restart {
	stop
	start
	return
}

echo -e "\n \033[40;32;1m \t*\033[m $COMMAND ADN SONDE \n"

case $COMMAND in
status)
    	status
    	;;
start|stop|restart)
    	if [ -z "$PIDADN" ] && [ -z "$PIDPERL" ] && [ "$COMMAND" = "stop" ]; then
        	exit 0
    	elif [ -n "$PIDADN" ] && [ -n "$PIDPERL" ] && [ "$COMMAND" = "start" ]; then
        	exit 0
    	elif [ -z "$PIDADN" ] && [ -z "$PIDPERL" ] && [ "$COMMAND" = "restart" ]; then
        	start
        	exit 0
    	elif [ "$COMMAND" = "stop" ]; then
		stop
		exit 0
    	elif [ "$COMMAND" = "start" ]; then
		start
		exit 0
    	elif [ $COMMAND = "restart" ]; then
		stop
		start
		exit 0
    	fi
    	;;
*)
    	echo -e "Unknow Command :\033[40;31;1m $COMMAND \033[m" 
    	echo "Usage : $JOB start|restart|stop|status\n"
    	exit 1
esac
